package com.example.neo4j.aop;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@EnableAspectJAutoProxy(exposeProxy = true, proxyTargetClass = true)
@Slf4j
public class LogAop {

    @Autowired
    private HttpServletRequest request;

    @Around("execution(* com.example.neo4j.controller..*.*(..))")
    public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String requestURI = request.getRequestURI();
        //获取操作类型
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //记录参数
        String[] parameterNames = methodSignature.getParameterNames();
        Map<String, Object> params = new HashMap<>();
        if (parameterNames != null && parameterNames.length > 0) {
            //获取参数的值
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < parameterNames.length; i++) {
                Object value = args[i];
                params.put(parameterNames[i], value);
            }

        }
        try {
            Object proceed = joinPoint.proceed();
            log.info("请求:{},参数:{},结果:{}", requestURI, JSONUtil.toJsonStr(params),proceed.toString());
            return proceed;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
